package create.com.modelproaction.activity.actionactivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import create.com.modelproaction.R;
import create.com.modelproaction.activity.BlueToothController;
import create.com.modelproaction.adapter.DeviceAdapter;
import create.com.modelproaction.entity.DeviceClass;
import create.com.modelproaction.entity.bluetoothdevice;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
//import BluetoothPackage.BluetoothController;
//import MyClass.DeviceAdapter;
//import MyClass.DeviceClass;
//————————————————
//        版权声明：本文为CSDN博主「veiinb」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/weiybin/article/details/130352162
/***
 * 蓝牙功能
 *
 * https://devbox.cn/p/112384709
 *
 * https://blog.csdn.net/weiybin/article/details/130352162
 */
public class BlueTooth2Activity extends AppCompatActivity {

    private Button btn_blu;
    private DeviceAdapter mAdapter1,mAdapter2;
    private List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表
    private List<DeviceClass> mfindDeviceList = new ArrayList<>();//搜索到的所有未绑定设备保存为列表
    private BlueToothController mbluetoothController = new BlueToothController();
    private Toast mToast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_btoothtwo);
        Init_Bluetooth();//开启蓝牙相关权限
        init_Filter();//初始化广播并打开
        Init_listView();//初始化设备列表
        show_bondDeviceList();//搜索展示已经绑定的蓝牙设备
    }

    //初始化蓝牙权限
    private void Init_Bluetooth(){
        //开启蓝牙位置共享
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
        mbluetoothController.enableVisibily(this);//让其他蓝牙看得到我
        mbluetoothController.turnOnBlueTooth(this,0);//打开蓝牙
    }
    //初始化列表，适配器的加载
    public void Init_listView(){
//        mAdapter1 = new DeviceAdapter(mbondDeviceList,BlueTooth2Activity.this );
//        ListView listView1 = (ListView)findViewById(R.id.listview1);
//        listView1.setAdapter(mAdapter1);
//        mAdapter1.notifyDataSetChanged();
        //listView1.setOnItemClickListener(toMainActivity2);//设备点击事件，点击设备名称后执行toMainActivity2
//        mAdapter2 = new DeviceAdapter(BlueTooth2Activity.this, R.layout.device_item, mfindDeviceList);
//        ListView listView2 = (ListView)findViewById(R.id.listview2);
//        listView2.setAdapter(mAdapter2);
//        mAdapter2.notifyDataSetChanged();
    }
    //开启广播
    private void init_Filter(){
        IntentFilter filter = new IntentFilter();
        //开始查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //结束查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //查找设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //设备扫描模式改变
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        //绑定状态
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(receiver, filter);
    }
    //广播内容
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                setSupportProgressBarIndeterminateVisibility(true);
                change_Button_Text("搜索中...","DISABLE");
                mfindDeviceList.clear();
//                mAdapter2.notifyDataSetChanged();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                setProgressBarIndeterminateVisibility(false);
                change_Button_Text("搜索设备","ENABLE");
            }
            //查找设备
            else if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                change_Button_Text("搜索中...","DISABLE");
                //查找到一个设备就添加到列表类中
                mfindDeviceList.add(new DeviceClass(device.getName(),device.getAddress()));
                mAdapter2.notifyDataSetChanged();//刷新列表适配器，将内容显示出来
            }
            else if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)){
                int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,0);
                if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
                    setProgressBarIndeterminateVisibility(true);
                }
                else {
                    setProgressBarIndeterminateVisibility(false);
                }
            }
            else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice remoteDecive = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(remoteDecive == null){
                    return;
                }
                int status = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, 0);
                if(status == BluetoothDevice.BOND_BONDED) {
                    showToast("已绑定" + remoteDecive.getName());
                } else if(status == BluetoothDevice.BOND_BONDING) {
                    showToast("正在绑定" + remoteDecive.getName());
                } else if(status == BluetoothDevice.BOND_NONE) {
                    showToast("未绑定" + remoteDecive.getName());
                }
            }
        }
    };
    //点击开始查找蓝牙设备
    public View findDevice(View view){
        mbluetoothController.findDevice();
        return view;
    }
    //查找已绑定的蓝牙设备
    private void show_bondDeviceList(){
        mbondDeviceList.clear();
        List<BluetoothDevice> bondDevices = mbluetoothController.getBondedDeviceList();//查找已绑定设备
        for(int i=0;i<bondDevices.size();i++){
            mbondDeviceList.add(new DeviceClass(bondDevices.get(i).getName(),bondDevices.get(i).getAddress()));
        }
//        mAdapter1.notifyDataSetChanged();
    }
    //点击按键搜索后按键的变化
    private void change_Button_Text(String text,String state){
//        Button button = (Button)findViewById(R.id.button1);
        if("ENABLE".equals(state)){
//            button.setEnabled(true);
//            button.getBackground().setAlpha(255); //0~255 之间任意调整
//            button.setTextColor(ContextCompat.getColor(this, R.color.black));
        }
        else {
//            button.setEnabled(false);
//            button.getBackground().setAlpha(150); //0~255 之间任意调整
//            button.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
        }
//        button.setText(text);
    }
    //点击设备后执行的函数
    private AdapterView.OnItemClickListener toMainActivity2 =new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
//            Intent intent = new Intent(BlueTooth2Activity.this,Main2Activity.class);
//            startActivity(intent);
        }
    };
    //设置toast的标准格式
    private void showToast(String text){
        if(mToast == null){
            mToast = Toast.makeText(this, text,Toast.LENGTH_SHORT);
            mToast.show();
        }
        else {
            mToast.setText(text);
            mToast.show();
        }
    }
}
